import { auth } from "@/lib/auth";
import {
  apiAuthPrefix,
  authRoutes,
  DEFAULT_LOGIN_REDIRECT,
  publicRoutes,
  apiPublicRoutes,
} from "../routes";
import { NextRequest, NextResponse } from "next/server";

export async function authMiddleware(req: NextRequest) {
  const session = await auth();
  const isLogin = !!session;
  const isApiAuthRoute = req.nextUrl.pathname.startsWith(apiAuthPrefix);
  const isApiPublicRoute = apiPublicRoutes.includes(req.nextUrl.pathname);
  const isPublicRoute = publicRoutes.includes(req.nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(req.nextUrl.pathname);

  if (req.nextUrl.pathname.startsWith("/api")) {
    if (isApiAuthRoute || isApiPublicRoute) {
      return null;
    } else {
      if (!isLogin) {
        return NextResponse.json(
          {
            code: 10001,
            message: "Forbidden",
          },
          { status: 401 }
        );
      }
    }
    return null;
  }

  if (isPublicRoute) {
    return null;
  } else {
    if (isAuthRoute) {
      if (isLogin) {
        return NextResponse.redirect(
          new URL(DEFAULT_LOGIN_REDIRECT, req.nextUrl)
        );
      }
      return null;
    }
    if (!isLogin) {
      return NextResponse.redirect(new URL("/auth/login", req.nextUrl));
    }
  }

  return null;
}
